<?php
/**
 * CN-FBA发货单物流（国内仓发fba仓）
 */
namespace App\Admin\Controllers\Delivery;

use App\Importer\Delivery\FBAImporter;
use App\Models\Basics\ExpressChannel;
use App\Models\Basics\ExpressCompany;
use App\Models\Delivery\FBADelivery;
use App\Models\Delivery\FBADeliveryLogistics;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class FBALogisticsUploadController extends AdminController{

    protected $title = 'CN至FBA-发货单物流';

    protected function grid()
    {
        $type = request('type');
        return view('delivery.fba-logistics-upload.index',compact('type'));
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $action = $request->get('action');
            $param = $request->get('param');
            if($param){
                $re = $this->{'_import'.$action}($file,$param);
            }else{
                $re = $this->{'_import'.$action}($file);
            }
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importLogistics(UploadedFile $file)
    {
        try {
            $data = Excel::toArray(new FBAImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            DB::beginTransaction();
            $errors = [];
            $count = 1;
            $arr = [];
            foreach($data as $row){
                $count++;
                $_deliveryNo = $row[0] ? trim($row[0]) : '';
                $expressCompanyId = $row[1] ? trim($row[1]) : '';
                $expressChannelId = $row[2] ? trim($row[2]) : '';
                $trackingNo = $row[3] ? trim($row[3]) : '';
                $totalWeight = $row[4] ? trim($row[4]) : '';
                $shippingFee = $row[5] ? trim($row[5]) : '';
                $otherFee = $row[6] ? trim($row[6]) : '';
                $arrivedAt = $row[7] ? RExcel::toDateTime(trim($row[7])) : '';
                if(!$_deliveryNo || !$expressCompanyId || !$expressChannelId){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                $deliveryNo = strtoupper($_deliveryNo);
                if(!in_array($deliveryNo,$arr)){
                    $arr[$count] = $deliveryNo;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                if($arrivedAt){
                    if(!strtotime($arrivedAt)){
                        $errors[$count] = "日期：".$arrivedAt."格式有误";
                        continue;
                    }
                }
                $expressCompanyIdFlag = ExpressCompany::existById($expressCompanyId);
                if(!$expressCompanyIdFlag){
                    $errors[$count] = $expressCompanyId.'系统不存在该物流公司';
                    continue;
                }
                $expressChannelIdFlag = ExpressChannel::existById($expressChannelId);
                if(!$expressChannelIdFlag){
                    $errors[$count] = $expressChannelId.'系统不存在该物流渠道';
                    continue;
                }
                $d = FBADelivery::query()->where('delivery_no', $deliveryNo)->first();
                if(!$d){
                    $errors[$count] = $_deliveryNo.'发货单不存在';
                    continue;
                }
                $logistics = FBADeliveryLogistics::query()->firstOrNew(['delivery_no' => $deliveryNo]);
                $logistics->express_company_id = $expressCompanyId;
                $logistics->area_id = $d->area_id;
                $logistics->express_channel_id = $expressChannelId;
                if($trackingNo){
                    $logistics->tracking_no = $trackingNo;
                }
                if($totalWeight){
                    $logistics->total_weight = $totalWeight;
                }
                if($shippingFee){
                    $logistics->shipping_fee = $shippingFee;
                }
                if($otherFee){
                    $logistics->other_fee = $otherFee;
                }
                if($arrivedAt){
                    $logistics->arrived_at = date('Y-m-d H:i:s',strtotime($arrivedAt));
                }
                $flag1 = $logistics->save();
                if(!$flag1){
                    DB::rollBack();
                }
                $d->logistics_status = 2;
                if($logistics->tracking_no){
                    $d->track_ex_status = 2;//已录入
                }
                $d->save();
            }
            DB::commit();
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    /**
     * 批量上传物流追踪号（仓库规格模板上传）
     * @param UploadedFile $file
     * @return array|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    private function _importLogisticsTrackingNo(UploadedFile $file)
    {
        try {
            $data = Excel::toArray(new FBAImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            DB::beginTransaction();
            $errors = [];
            $count = 1;
            $trackingNoArr = [];
            foreach($data as $row){
                $count++;
                $_deliveryNo = $row[0] ? trim($row[0]) : '';
                $_trackingNo = $row[1] ? trim($row[1]) : '';
                if(!$_deliveryNo || !$_trackingNo){
                    $errors[$count] = ',必填项为空';
                    continue;
                }
                $deliveryNo = strtoupper($_deliveryNo);
                $deliveryObj = FBADelivery::query()->where('delivery_no', $deliveryNo)->first();
                if(!$deliveryObj){
                    $errors[$count] = $_deliveryNo.',发货单不存在';
                    continue;
                }

                $trackingNoArr[$deliveryNo][] = $_trackingNo; //追踪号集合
            }

            if(empty($errors)){
                foreach ($trackingNoArr as $key => $val){
                    $uniqueArray = array_unique($val); //数组去重
                    $trackingNos = implode(',',$uniqueArray); //追踪号(字符串','拼接)

                    //物流
                    $logistics = FBADeliveryLogistics::query()->firstOrNew(['delivery_no' => $key]);
                    $logistics->tracking_no = $trackingNos;
                    $flag = $logistics->save();
                    if(!$flag){
                        continue;
                    }

                    //发货单
                    $delivery = FBADelivery::query()->where('delivery_no', $key)->first();
                    if(!$delivery){
                        continue;
                    }
                    $delivery->logistics_status = 2; //物流已更新
                    if($logistics->tracking_no){
                        $delivery->track_ex_status = 2;//运单号已录入
                    }
                    $flag1 = $delivery->save();
                    if($flag1){
                        DB::commit();
                    }else{
                        DB::rollBack();
                    }
                }

                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }

        } catch (\Exception $e) {
            DB::rollBack();
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
